import { useState } from 'react'
import styles from './index.module.scss'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import axios from 'axios'
import { Toast } from 'antd-mobile'

let timer = -1

function Login ({ history }) {
  const [time, setTime] = useState(0)

  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810'
    },
    // 表单验证，此处，我们使用 Yup 包来进行验证
    // 参考：https://formik.org/docs/tutorial#schema-validation-with-yup
    validationSchema: Yup.object({
      // required() 的参数就是：验证失败时的错误信息
      mobile: Yup.string()
        .required('手机号为必填项')
        .matches(/^1[3-9]\d{9}$/, '手机号码格式不正确'),
      code: Yup.string()
        .required('验证码为必填项')
        .matches(/^\d{6}$/, '验证码格式错误')
    }),
    onSubmit: async values => {
      const res = await axios.post(
        'http://geek.itheima.net/v1_0/authorizations',
        values
      )

      if (res.data.message.toLowerCase() === 'ok') {
        Toast.show({
          icon: 'success',
          content: '登录成功~'
        })

        history.push('/home')

        // 保存token
        localStorage.setItem('geek-app', JSON.stringify(res.data.data))
      }
    }
  })

  const getCode = async () => {
    if (time > 0) return

    setTime(4)
    console.log('--getCode--')
    clearInterval(timer)
    timer = setInterval(() => {
      // setTime(time-1)
      setTime(time => {
        console.log('---setInterval---', time)
        if (time <= 1) {
          clearInterval(timer)
        }

        return time - 1
      })
    }, 1000)
  }

  const {
    handleSubmit,
    handleChange,
    handleBlur,
    values: { mobile, code },
    // 表示当前表单项是否被”摸过“（ 可以理解是否访问过 ）
    touched,
    // 表单验证失败时的错误信息
    errors
  } = formik

  return (
    <div className={styles.root}>
      <h1 className='title'>账号登录</h1>
      <div className='login-wrap'>
        <form onSubmit={handleSubmit}>
          <div className='form-item'>
            <input
              name='mobile'
              type='text'
              onChange={handleChange}
              onBlur={handleBlur}
              placeholder='请输入手机号'
              value={mobile}
            />
            <div className='error'>
              {touched.mobile && errors.mobile ? (
                <div>{errors.mobile}</div>
              ) : null}
            </div>
          </div>

          <div className='form-item'>
            <input
              name='code'
              type='text'
              onChange={handleChange}
              onBlur={handleBlur}
              placeholder='请输入验证码'
              value={code}
            />
            <span onClick={getCode}>
              {time <= 0 ? '获取验证码' : `${time}s`}
            </span>
            <div className='error'>
              {touched.code && errors.code ? <div>{errors.code}</div> : null}
            </div>
          </div>
          <div className='form-item'>
            <button type='submit'>登录</button>
          </div>
        </form>
      </div>
    </div>
  )
}

export default Login
